import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 导入一级路由
import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'
// 搜索页面是一级路由，没有下面的导航
import Search from '@/views/search'
import Result from '@/views/search/result'
import Detail from '@/views/article'
// 用户编辑资料的路由
import Edit from '@/views/layout/user/edit'

// 导入二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: Result
  },
  {
    path: '/detail/:id',
    component: Detail
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

const loginURL = ['/user', '/qa', '/user/edit']

// 导航守卫，没有token
router.beforeEach(function (to, from, next) {
  const token = store.state.user.tokenobj.token

  if (token) {
    // 直接放行
    next()
  } else {
    if (loginURL.some((item) => item === to.path)) {
      // 导航路障，等待导航守卫过程中又跳转了新的导航
      // 本来要跳转user但是跳到了login
      // next('/login')
      // router.push('/login')
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
